﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Yahoo.Yui.Compressor;

namespace JSCompressor
{
    class Program
    {
        static void Main(string[] args)
        {
            
            var input = args[0];
            var output = args[1];

            if (!Directory.Exists(output))
            {
                throw new ArgumentException(string.Format("The output directory '{0}' doesn't exist", output));
            }
            if (Directory.Exists(input))
            {
                CompressDirectory(input, output);
            }
            else if (File.Exists(input))
            {
                CompressFile(input, output);
            }
            else
            {
                throw new ArgumentException(string.Format("{0} isn't a known directory or file", input));
            }
        }

        public static void CompressDirectory(string root, string outputDirectory)
        {
            Console.WriteLine("Compressing all .js files within: " + root);
            foreach (var file in Directory.GetFiles(root, "*.js"))
            {
                CompressFile(file, outputDirectory);
            }
            foreach (var directory in Directory.GetDirectories(root))
            {
                //skip .svn folders and what not    
                if ((new DirectoryInfo(directory).Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
                {
                    var newOuputDirectory = outputDirectory + directory.Substring(root.Length) + "\\";
                    CompressDirectory(directory, newOuputDirectory);
                }
            }
        }
        public static void CompressFile(string file, string outputDirectory)
        {
            var name = Path.GetFileName(file);
            Console.WriteLine("Compressing file: " + name);
            using (var sw = new StreamWriter(outputDirectory + name))
            using (var sr = new StreamReader(file))
            {
                var compressed = JavaScriptCompressor.Compress(sr.ReadToEnd(), false);
                sw.Write(compressed);
            }

        }
    }
}
